import json

from fastapi import Request, APIRouter


from core.Response import success
from models.models import Post
from schemas.posts import serialize_posts


router = APIRouter(prefix='')


# @router.get("/{id}", )
# async def get_posts(request: Request, id: int):
#     print("get_posts" * 10, id)
#     print()
#     posts=await request.app.state.cache.get('posts')
#     print(posts)
#     queryset = await Post.get_or_none(id=id)  # 假设你使用的是Tortoise ORM
#
#     return {
#         "code": 0,
#         "data": posts,
#     }
#
#
@router.post("", response_model=dict)
async def create_post(request: Request):

    # 尝试从缓存中获取数据
    cached_posts = await request.app.state.cache.get('row')
    if cached_posts:
        print("从缓存中获取数据")
        return success(data=json.loads(cached_posts))
    print("从数据库中获取数据")

    recent_posts_queryset = await Post.filter(tags=1).order_by('id').limit(12)
    recent_posts = await serialize_posts(recent_posts_queryset)


    slider_posts_queryset = await Post.filter(tags=2).order_by('id').limit(12)
    slider_posts = await serialize_posts(slider_posts_queryset)


    # 将 Pydantic 模型转换为字典
    cospaly_posts_dict = [post.dict() for post in recent_posts]
    slider_posts_dict = [post.dict() for post in slider_posts]


    response_data = {
        'cosp': cospaly_posts_dict,
        'danji': slider_posts_dict,

    }
    print(response_data)

    # 将数据序列化为 JSON 字符串并存入缓存
    await request.app.state.cache.set('row', json.dumps(response_data, default=str),ex=259200)

    return success(data=response_data)
